import json
from urllib3 import *
from base64 import b64encode
import re


def config_interface_ip(ip,username,password,interface,address,mask):
    disable_warnings()
    http = PoolManager()

    headers = {}

    headers['Accept'] = 'application/yang-data+json'
    headers['Content-Type'] = 'application/yang-data+json'

    user_pass_str = username + ':' + password
    user_pass_str_encode = user_pass_str.encode()
    userAndPass = b64encode(user_pass_str_encode).decode("ascii")

    headers["Authorization"] = 'Basic %s' % userAndPass

    interface_name, interface_no = re.match('([a-zA-Z]*)([0-9].*)', interface).groups()

    url = "https://" + ip + "/restconf/data/Cisco-IOS-XE-native:native/interface/" + interface_name + "=" + interface_no + "/ip/address/primary"
    json_data = {
                "Cisco-IOS-XE-native:primary":{
                "address": address,
                "mask": mask
                }
                }
    r = http.request('PATCH', url, headers=headers, body=json.dumps(json_data))  # 使用POST发起请求,并且使用认证头部
    print(r.data.decode())

if __name__ == "__main__":
    username = "admin"
    password = "Cisc0123"
    ip = "10.1.1.253"
    config_interface_ip(ip, username, password, "GigabitEthernet3", "54.4.4.4", "255.255.255.0")